package com.etoak.car.controller;

import com.alibaba.fastjson.JSONObject;
import com.etoak.car.bean.Car;
import com.etoak.car.bean.Export;
import com.etoak.car.bean.Order;
import com.etoak.car.bean.Users;
import com.etoak.car.mapper.UserMapper;
import com.etoak.car.service.OrderService;
import com.etoak.car.service.UserService;
import com.etoak.commons.enums.ETEnums;
import com.etoak.commons.page.Page;
import com.etoak.commons.redis.RedisUtil;
import com.etoak.commons.response.ETResponse;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;
    UserService userService;

    /**
     * 管理员的订单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping
    public ETResponse queryOrder(@RequestParam(required = false,defaultValue = "1") int pageNum, @RequestParam(required = false,defaultValue = "2") int pageSize){

        Page<Order> order = orderService.querySome(pageNum,pageSize);

        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData(order);
        return response;

    }
    /**
     * 删除订单信息
     */
    @PostMapping(value = "/{id}")
    public ETResponse delUser(@PathVariable int id){
        orderService.delOrder(id);

        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData("成功");
        return response;

    }

    /**
     * 用户查看订单
     * @param pageNum
     * @param pageSize
     * @param token
     * @return
     */
    @RequestMapping("/user")
    public ETResponse queryOrder(@RequestParam(required = false,defaultValue = "1") int pageNum, @RequestParam(required = false,defaultValue = "4") int pageSize,@RequestParam("token") String token){

//        RedisUtil ru = RedisUtil.getRedisUtil();
//        String userInfo = ru.get(token);
//        Users u = JSONObject.parseObject(userInfo, Users.class);
//        int id = u.getId();
        int id = Integer.parseInt(token);
        Page<Order> order = orderService.querySomeUser(pageNum,pageSize,id);

        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData(order);
        return response;

    }

    @RequestMapping("/huanCar")
    public ETResponse huanCar(int id,int userid,int carid,String token) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        double time = System.currentTimeMillis();
        String huandate = sdf.format(time);
        //获得租车时间
        Order order = orderService.queryDate(id);
        String zudate = order.getZudate();
        double zu = sdf.parse(zudate).getTime();
        System.out.println(zu);
        //计算时长
        double sum =1;
                //(time-zu)/1000/60/60;
        //改变订单还车时间
        orderService.upHuanCarTime(huandate,id);
        //根据cheid更新车辆状态
        orderService.upCarStatus(carid);
        //根据id拿到车辆单价
        Car car = orderService.getCarPrice(carid);
        double price = car.getPrice();


        ETResponse response = new ETResponse();
        //查看用户是否有前
        Users users = orderService.queryMoney(userid);

        if(users.getVip()==1){
            //根据用户id扣去前
            double orderPrice = sum*price*0.8;
//            double jifen=users.getJifen();
//            jifen+=orderPrice;
//            System.out.println(jifen);
//            userService.upOrderjifen(id);
//            userService.upJifen(id);
            if(users.getMoney()<orderPrice){
                //更新钱
                orderService.upOrderUserMoney(userid,users.getMoney());
                Users user = orderService.queryMoney(userid);
                //更新redis
                RedisUtil ru = RedisUtil.getRedisUtil();
                ru.setex(token, 1800 * 365 * 24, JSONObject.toJSONString(user));

                response.setCode(ETEnums.SUCCESS.getCode());
                response.setMsg(ETEnums.SUCCESS.getMsg());
                response.setData("余额不足，联系管理员充值，已还车");
            }else {
                //给订单赋值
                orderService.setZuMoney(userid,carid,orderPrice);
                orderService.upOrderUserMoney(userid, orderPrice);
                Users user1 = orderService.queryMoney(userid);
                //更新redis
                RedisUtil ru = RedisUtil.getRedisUtil();
                ru.setex(token, 1800 * 365 * 24, JSONObject.toJSONString(user1));
                response.setCode(ETEnums.SUCCESS.getCode());
                response.setMsg(ETEnums.SUCCESS.getMsg());
                response.setData("扣费成功，已还车");
            }
        }else {
            double orderPrice = sum*price;
            if(users.getMoney()<orderPrice){
                //更新钱
                orderService.upOrderUserMoney(userid,users.getMoney());
                Users user = orderService.queryMoney(userid);
                //更新redis
                RedisUtil ru = RedisUtil.getRedisUtil();
                ru.setex(token, 1800 * 365 * 24, JSONObject.toJSONString(user));

                response.setCode(ETEnums.SUCCESS.getCode());
                response.setMsg(ETEnums.SUCCESS.getMsg());
                response.setData("余额不足，联系管理员充值，已还车");
            }else {
                //给订单赋值
                orderService.setZuMoney(userid,carid,orderPrice);
                orderService.upOrderUserMoney(userid, orderPrice);
                Users user1 = orderService.queryMoney(userid);
                //更新redis
                RedisUtil ru = RedisUtil.getRedisUtil();
                ru.setex(token, 1800 * 365 * 24, JSONObject.toJSONString(user1));
                response.setCode(ETEnums.SUCCESS.getCode());
                response.setMsg(ETEnums.SUCCESS.getMsg());
                response.setData("扣费成功，已还车");
            }
        }


        return response;


    }
    //导出
    @ResponseBody
    @RequestMapping(value = "/export2Excel",method = RequestMethod.GET)
    protected void export2Excel(String ids, HttpServletResponse response)throws Exception {
        String[] idss = null;
        if(ids!=null){
            idss = ids.split(",");
        }
        //获得数据

        List<Order> books = orderService.queryByIds(idss);
        //创建一个excel表格
        Workbook wb = new XSSFWorkbook();
        //创建一个sheet
        Sheet sheet = wb.createSheet("order列表");
        //添加行
        Row header = sheet.createRow(0);
        /*header.createCell(0).setCellValue("序号");
        header.createCell(1).setCellValue("学生");
        header.createCell(2).setCellValue("年龄");
        header.createCell(3).setCellValue("生日");*/
        Class cls = Order.class;
        Field[] fs = cls.getDeclaredFields();
        for(Field f:fs){
            Annotation ans[] = f.getDeclaredAnnotations();
            for(Annotation an:ans){
                if(an.annotationType()== Export.class){
                    Export export = (Export) an;
                    header.createCell(export.index()).setCellValue(export.name());
                }
            }
        }

        //把数据放进刚刚创建的表格
        try {
            int k = 1;
            for (Order book : books) {
                Row data = sheet.createRow(k++);

                for (Field f : fs) {
                    Annotation ans[] = f.getDeclaredAnnotations();
                    for (Annotation an : ans) {
                        if (an.annotationType() == Export.class) {
                            Export export = (Export) an;
                            //破封装
                            f.setAccessible(true);
                            data.createCell(export.index()).setCellValue(f.get(book)+"");
                        }
                    }
                }
            /*data.createCell(0).setCellValue(k-1);
            data.createCell(1).setCellValue(stu.getName());
            data.createCell(2).setCellValue(stu.getAge());
            data.createCell(3).setCellValue(stu.getBirth());*/

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //OutputStream os = new FileOutputStream(new File("a.xlsx"));
        response.setHeader("Content-Disposition","attachment;filename=order.xlsx");

        wb.write(response.getOutputStream());

        //wb.close();

    }
}
